import React, { Component } from "react";

const Context = React.createContext();

const Provider = Context.Provider;
const Consumer = Context.Consumer;

//WidthConsumer高阶组件，它根据配置返回一个高阶组件
const widthConsumer = (Consumer) => (Comp) => (props) => {
  return <Consumer>{(value) => <Comp {...value} />}</Consumer>;
};

//经过widthConsumer(Consumer)返回的高阶组件包装，Child获得了上下文中的值
const Child = widthConsumer(Consumer)((props) => {
  return (
    <h1 style={{ textAlign: "center" }} onClick={(val) => props.add()}>
      {props.counter}
    </h1>
  );
});

class ContextTest extends Component {
  state = {
    counter: 0,
  };

  add = () => {
    this.setState({ counter: this.state.counter + 1 });
  };

  render() {
    return (
      <div>
        <Provider value={{ counter: this.state.counter, add: this.add }}>
          <Child />
          <Child />
          <Child />
        </Provider>
      </div>
    );
  }
}

export default ContextTest;
